import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, InputNumber, Space, Switch } from 'antd';

import Upload from '@/components/upload';

import { store } from '@/store';

import { AppApiStatus, AppStatus } from '@/enum/app';
import {
  sysApplicationAdd,
  sysApplicationGetVo,
  sysApplicationUpdate
} from '@/services/base/quanxianmokuaiyingyongbiaojiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      const query = {
        ...values,
        status: (values.status as unknown as boolean) === true ? AppStatus.启用 : AppStatus.禁用,
        apiStatus:
          (values.apiStatus as unknown as boolean) === true ? AppApiStatus.启用 : AppApiStatus.禁用
      };

      if (query.receiveObj) {
        query.receiveObj = JSON.stringify(query.receiveObj);
      }

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? sysApplicationUpdate(query) : sysApplicationAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(async () => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            const res = (
              await sysApplicationGetVo({
                id: arg.rowData!.id as unknown as string
              })
            ).data;

            if (res) {
              // 回填数据
              form.setFieldsValue({
                ...res,
                appIcon: res.appIcon ? [res.appIcon] : [],
                status: res.status === AppStatus.启用,
                apiStatus: res.apiStatus === AppApiStatus.启用
              });
            }
          } else {
            form.resetFields();
            form.setFieldsValue({
              status: true,
              apiStatus: true
            });
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增应用',
          edit: '编辑应用',
          detail: '应用详情'
        }[args?.type as string]
      }
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSave}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="应用图标"
          name="appIcon"
          rules={[
            {
              required: true,
              message: '请上传应用图标'
            }
          ]}
        >
          <Upload base64 showUploadList={false} accept="image/*">
            <div>上传</div>
          </Upload>
        </Form.Item>
        <Form.Item
          label="应用名称"
          name="appName"
          rules={[
            {
              required: true,
              message: '请输入应用名称'
            }
          ]}
        >
          <Input placeholder="请输入应用名称" />
        </Form.Item>
        <Form.Item
          label="code过期时间（秒）"
          name="codeExpired"
          rules={[
            {
              required: true,
              message: '请输入code过期时间（秒）'
            }
          ]}
        >
          <InputNumber placeholder="请输入code过期时间（秒）" min={0} step={1} />
        </Form.Item>
        <Form.Item
          label="回调地址"
          name="redirectUrl"
          rules={[
            { required: true, message: '请输入回调地址' },
            {
              pattern:
                /(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?\/[a-zA-Z0-9]{2,}|((https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?)|(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})?/g,
              message: '请输入正确的回调地址'
            }
          ]}
        >
          <Input placeholder="请输入回调地址" />
        </Form.Item>
        <Form.Item label="应用状态" name="status" valuePropName="checked">
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>
        <Form.Item label="API状态" name="apiStatus" valuePropName="checked">
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
